#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
富铭业务相关特殊接口
"""
import datetime
from flask_jwt_extended import jwt_required
from lj_action import action_data
from lj_api import tool_flask
from lj_tool import tool_auth, tool_cache

api_fm = tool_flask.Blueprint('api_fm', __name__)


@api_fm.route("/<tenant>/login", methods=["GET", "POST"])
@tool_flask.lj_flask_valid(
    tool_flask.LJVaildRule('username', True),
    tool_flask.LJVaildRule('password', True),
)
def login(tenant):
    account_orm = action_data.init_action_data('users', f'fm_tenant_{tenant}')

    username = tool_flask.get_param("username")
    password = tool_flask.get_param("password")

    accounts = account_orm.listFilter(account_orm.entity.account == username)

    if len(accounts) > 0:
        return tool_auth.lj_auth_gen_token(identity=accounts[0].get('id'), additional_claims={'lj_group_id': accounts[0].get('group_id')})
    else:
        return '账号密码错误,登录失败...', 500,


@api_fm.route("/<tenant>/list-site-mns", methods=["GET", "POST"])
@jwt_required()
def list_siteMns(tenant):
    return list_cache_mns(tenant, tool_auth.get_data('lj_group_id'))


@tool_cache.lj_wrapper_cache('fm_list_cache_mns', 60 * 5)
def list_cache_mns(tenant, group_id):
    group_item_orm = action_data.init_action_data(
        'groupables', f'fm_tenant_{tenant}')
    return [row.get('groupable_id') for row in group_item_orm.listFilter(group_item_orm.entity.group_id == group_id)]
